<template>
  <div>
    <center>
    <div><h2>欢迎登陆~</h2></div>
    <div id="formDiv">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登陆</el-button>
          <el-button type="success" @click="regist">去注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </center>
  </div>
</template>

<script>
  export default {
    name: "Login",
    data() {
      return {
        user: {
          username: '',
          password: ''
        },
      }
    },
    methods: {
      login() {
        console.log('login~');
        let url = 'http://localhost:80/user/login';
        this.axios.post(url, this.user).then(resp => {
          console.log(resp);
          let vo = resp.data;
          if (vo.success){
            //弹消息
            this.$message({
              message: vo.data.username + ' 登陆成功~',
              type: 'success'
            });
            //存储登陆标记到sessionStorage
            sessionStorage.setItem('isLogin', 'true');
            //把登陆的用户存入vuex空间中
            this.$store.dispatch('asyncUpdateUser', vo.data);
            console.log("this.$store--->" + this.$store);
            //去首页
            setTimeout(() => {
              this.$router.push('/home')
            },1000)
          } else {
            this.user.username = '';
            this.user.password = '';
            this.$message({
              message: vo.message,
              type: 'error'
            })
          }
        }).catch(error => {
          console.log("失败了" + error);
        })
      },

      regist() {
        this.$router.push('/regist')
      }
    }
  }

</script>

<style scoped>
  #formDiv{
    width: 500px;
  }
</style>
